package luj.tool.jnproxyan.proxy.network.socks.actor.root.message.http.client2p.request.flush;

import io.netty.channel.Channel;
import io.netty.handler.codec.http.HttpObject;
import luj.tool.jnproxyan.proxy.network.logger.Proxy2sLogger;
import luj.tool.jnproxyan.proxy.network.socks.actor.root.Socks5Actor;
import luj.tool.jnproxyan.proxy.network.socks.request.op.SocksReqGetter;
import luj.tool.jnproxyan.proxy.network.socks.request.SocksRequest;
import luj.tool.jnproxyan.proxy.network.direct.state.P2sConn;
import luj.tool.jnproxyan.proxy.network.direct.state.P2sConnAttr;
import luj.tool.jnproxyan.proxy.stats.http.history.History021ReqUpdater;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Deque;

@Component
final class OnHttpReqFlush implements Socks5Actor.Handler<HttpReqFlushMsg> {

  @Override
  public void onHandle(Context ctx) throws Exception {
    Socks5Actor self = ctx.getActorState(this);
    HttpReqFlushMsg msg = ctx.getMessage(this);

    Long socksId = msg.reqId();
    SocksRequest req = _reqGetter.inject(self, socksId).getReq();

    Channel p2sConn = req.getP2sConn3();
    Deque<HttpObject> httpQueue = req.getWebReqQueue();

    var p2sLog = new Proxy2sLogger(LOG, socksId);
    if (p2sConn == null) {
      p2sLog.log("连接未就绪：等待，请求数：{}", httpQueue.size());
      return;
    }

    if (httpQueue.isEmpty()) {
      // 包都发完了
      return;
    }

    HttpObject httpObj = httpQueue.pollFirst();
    p2sLog.log("排到发送：{}", httpObj.getClass().getName());
    _historyUpdater.inject(self.getHttpHistoryDat(), socksId, httpObj).update();

    P2sConn connState = new P2sConnAttr(p2sConn).get();
    connState.getHttpsCli().send(httpObj);

    // 下一个
    ctx.getActorRef().tell(msg);
  }

  private static final Logger LOG = LoggerFactory.getLogger(OnHttpReqFlush.class);

  @Autowired
  SocksReqGetter _reqGetter;

  @Autowired
  History021ReqUpdater _historyUpdater;
}
